//
// Created by Zhang on 2021/3/31.
//

#include "q21.h"
#include "stdio.h"
#include "time.h"
#include "stdlib.h"

int sum_matrix(int **matrix, int n) {
    int sum = 0;
    int **p1 = matrix;
    for (int m = 0; m < n; m++) {

        int *p2 = *p1;
        for (int j = 0; j < n; j++) {
            sum += *p2;
            p2++;
        }
        p1++;
    }


    return sum;


}

int **create_matrix(int n) {
    srand((int) time(NULL));
    int **p = (int **) malloc(sizeof(int *) * n);
    int **pp = p;
    for (int i = 0; i < n; i++) {
        pp = p + i;
        *pp = (int *) malloc(sizeof(int *) * n);
    }

    int **p1 = p;
    for (int m = 0; m < n; m++) {
        int *p2 = *p1;
        for (int j = 0; j < n; j++) {

            *p2 = rand() * 0.01;
//            printf("%d ", *p2);
            p2++;
        }
        p1++;
//        printf("\n");
    }
    return p;
}

void free_matrix(int **p, int n) {
    int **pp = p;
    for (int i = 0; i < n; i++) {
        int *ppp = *pp;
        pp++;
        free(ppp);
    }
    free(p);
}

int unit_test_21(int n) {
    int **p;
    p = create_matrix(n);
    printf("%d\n", sum_matrix(p, n));
    free_matrix(p, n);
    return 1;
}